package com.ccx.coachsite.http;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import com.ccx.coachsite.data.SystemConst;
import com.ccx.coachsite.util.Log;
import com.ccx.coachsite.util.StreamUtil;

public class ImageGetter extends AsyncTask<String, Integer, Bitmap> {

	private HttpURLConnection conn;
	private ProgressListener<BitmapProgress> listener;
	private BitmapProgress progress;

	private File mFile;

	public ImageGetter() {
		progress = new BitmapProgress();
	}

	public ImageGetter(String fileDir, String fileName) {
		this();
		init(fileName, fileDir);
	}

	private void init(String fileName, String fileDir) {
		File dir = new File(fileDir);

		if (!dir.exists()) {
			dir.mkdirs();
		}

		mFile = new File(fileDir, fileName);
	}

	@Override
	protected final Bitmap doInBackground(String... params) {

		if (params == null || params.length <= 0) {
			Log.e("url is null, download exit.");
			return null;
		}

		Bitmap bitmap = null;
		FileOutputStream f = null;

		String url = params[0];
		Log.d("url:" + url);
		try {
			URL u = new URL(url);
			conn = ((HttpURLConnection) u.openConnection());
			
			//URL url = new URL(imgurl);
			//URLConnection con = url.openConnection();
			//连接超时时间设置为10秒
			conn.setConnectTimeout(SystemConst.CONNECTION_TIMEOUT);
			conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6");
			
			//conn.setConnectTimeout(2000);
			//conn.setRequestMethod("GET");
			
			//conn.setDoOutput(true);
			//conn.setUseCaches(true);
			conn.connect();
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
				return null;

			InputStream in = conn.getInputStream();

			if (mFile != null) {
				f = createOutputStream(mFile);
				if (f == null) {
					Log.e("FileOutputStream is null, download exit.");
					return null;
				}
				int total = conn.getContentLength();
				int fix = 0;

				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = in.read(buffer)) > 0) {
					f.write(buffer, 0, len);
					fix += len;
					publishProgress(total, fix);
				}

				bitmap = BitmapFactory.decodeFile(mFile.getAbsolutePath());
			} else {
				bitmap = BitmapFactory.decodeStream(in);
			}

		} catch (Exception e) {
			// e.printStackTrace();
			Log.e(e.getMessage(), e);
		} finally {
			// Closes this connection.
			if (conn != null)
				conn.disconnect();
			if (f != null)
				StreamUtil.closeSilently(f);
		}
		return bitmap;
	}

	@Override
	protected final void onPostExecute(Bitmap result) {
		if (listener != null) {
			progress.setBitmap(result);
			listener.onPostExecute(progress);
		}
	}

	private FileOutputStream createOutputStream(File file) {
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			Log.e(e.getMessage() + ", file absolutePath:"
					+ file.getAbsolutePath(), e);
			// e.printStackTrace();
		}

		return out;
	}

	public void setProgressListener(ProgressListener<BitmapProgress> l) {
		listener = l;
	}
}
